package cn.com.thingo.hyintelligent.ui.activity;


import android.Manifest;
import android.content.Intent;
import android.content.pm.PackageManager;
import android.support.annotation.NonNull;
import android.support.v4.content.ContextCompat;
import android.view.View;
import android.widget.Button;
import android.widget.ImageView;
import android.widget.LinearLayout;
import android.widget.TextView;

import com.bumptech.glide.Glide;
import com.bumptech.glide.load.engine.DiskCacheStrategy;
import com.bumptech.glide.request.RequestOptions;
import com.luck.picture.lib.PictureSelector;
import com.luck.picture.lib.config.PictureConfig;
import com.luck.picture.lib.config.PictureMimeType;
import com.luck.picture.lib.entity.LocalMedia;
import com.th.opensdk.openapi.THOpenSDK;


import java.io.File;
import java.util.ArrayList;
import java.util.List;

import butterknife.BindView;
import butterknife.OnClick;
import cn.com.thingo.hyintelligent.R;
import cn.com.thingo.hyintelligent.base.BaseActivity;
import cn.com.thingo.hyintelligent.base.contract.PersonalContract;
import cn.com.thingo.hyintelligent.model.bean.CommonBean;
import cn.com.thingo.hyintelligent.model.bean.ModifyHeadBean;
import cn.com.thingo.hyintelligent.model.bean.UserBean;
import cn.com.thingo.hyintelligent.model.http.api.ShouCheApis;
import cn.com.thingo.hyintelligent.permission.PermissionHelper;
import cn.com.thingo.hyintelligent.permission.PermissionInterface;
import cn.com.thingo.hyintelligent.permission.PermissionUtil;
import cn.com.thingo.hyintelligent.presenter.PersonalPresenter;
import cn.com.thingo.hyintelligent.util.SPUtils;
import okhttp3.MediaType;
import okhttp3.MultipartBody;
import okhttp3.RequestBody;

/**
 * 个人中心
 */
public class PersonalActivity extends BaseActivity<PersonalPresenter> implements PersonalContract.View, PermissionInterface {
    @BindView(R.id.personal_head_pic)
    ImageView ivHead;
    @BindView(R.id.personal_head_name)
    TextView tvName;
    @BindView(R.id.personal_head_gateway)
    TextView tvGateway;
    @BindView(R.id.personal_head_edit)
    ImageView ivHeadEdit;
    @BindView(R.id.personal_my_gateway)
    LinearLayout llMyGateway;
    @BindView(R.id.personal_my_auth)
    LinearLayout llMyAuth;
    @BindView(R.id.personal_message)
    LinearLayout llMessage;
    @BindView(R.id.personal_logout)
    Button btnLogout;
    @BindView(R.id.toolbar_left)
    ImageView ivLeft;
    @BindView(R.id.toolbar_title)
    TextView tvTitle;
    @BindView(R.id.personal_auth_fold)
    LinearLayout llAuthFold;
    @BindView(R.id.personal_my_auth_icon)
    ImageView ivAuthIcon;
    private List<LocalMedia> selectList = new ArrayList<>();


    //要申请的权限
    private String[] mPermissions = {Manifest.permission.READ_EXTERNAL_STORAGE, Manifest.permission.WRITE_EXTERNAL_STORAGE, Manifest.permission.CAMERA};
    private PermissionHelper permissionHelper;


    @Override
    protected int getLayout() {
        return R.layout.activity_personal;
    }

    @Override
    protected void initEventAndData() {
        initView();
        //初始化权限
        permissionHelper = new PermissionHelper(this, this);
    }

    private void initView() {
        ivLeft.setImageResource(R.mipmap.back);
        tvTitle.setText(R.string.personal);
    }

    @Override
    protected void initInject() {
        getActivityComponent().inject(this);
    }

    @Override
    protected void onResume() {
        super.onResume();
        initData();
    }

    private void initData() {
        mPresenter.getUser(SPUtils.newInstance().getString(SPUtils.LOGIN_TOKEN));
    }

    @OnClick({R.id.personal_head_pic, R.id.personal_head_edit, R.id.personal_my_gateway, R.id.personal_my_auth,
            R.id.personal_message, R.id.personal_logout, R.id.toolbar_left, R.id.personal_modify_password, R.id.personal_auth_gateway,
            R.id.personal_auth_monitor, R.id.personal_auth_door})
    public void onClick(View view) {
        switch (view.getId()) {
            case R.id.personal_head_pic:
                if (ContextCompat.checkSelfPermission(PersonalActivity.this,
                        Manifest.permission.WRITE_EXTERNAL_STORAGE)
                        != PackageManager.PERMISSION_GRANTED) {
                    //申请权限
                    permissionHelper.requestPermissions();
                } else {
                    PictureSelector.create(PersonalActivity.this)
                            .openGallery(PictureMimeType.ofImage())//全部.PictureMimeType.ofAll()、图片.ofImage()、视频.ofVideo()、音频.ofAudio()
                            .maxSelectNum(1)// 最大图片选择数量 int
                            .minSelectNum(1)// 最小选择数量 int
                            .selectionMode(PictureConfig.SINGLE)// 多选 or 单选 PictureConfig.MULTIPLE or PictureConfig.SINGLE
                            .previewImage(true)// 是否可预览图片 true or false
                            .previewVideo(false)// 是否可预览视频 true or false
                            .enablePreviewAudio(false) // 是否可播放音频 true or false
                            .isCamera(true)// 是否显示拍照按钮 true or false
                            .imageFormat(PictureMimeType.PNG)// 拍照保存图片格式后缀,默认jpeg
                            .isZoomAnim(true)// 图片列表点击 缩放效果 默认true
                            .enableCrop(true)// 是否裁剪 true or false
                            .compress(true)// 是否压缩 true or false
                            .glideOverride(160, 160)// int glide 加载宽高，越小图片列表越流畅，但会影响列表图片浏览的清晰度
                            .withAspectRatio(1, 1)// int 裁剪比例 如16:9 3:2 3:4 1:1 可自定义
                            .hideBottomControls(false)// 是否显示uCrop工具栏，默认不显示 true or false
                            .isGif(false)// 是否显示gif图片 true or false
                            .freeStyleCropEnabled(true)// 裁剪框是否可拖拽 true or false
                            .circleDimmedLayer(true)// 是否圆形裁剪 true or false
                            .showCropFrame(false)// 是否显示裁剪矩形边框 圆形裁剪时建议设为false   true or false
                            .showCropGrid(false)// 是否显示裁剪矩形网格 圆形裁剪时建议设为false    true or false
                            .openClickSound(true)// 是否开启点击声音 true or false
                            .selectionMedia(selectList)// 是否传入已选图片 List<LocalMedia> list
                            .previewEggs(true)// 预览图片时 是否增强左右滑动图片体验(图片滑动一半即可看到上一张是否选中) true or false
                            .minimumCompressSize(100)// 小于100kb的图片不压缩
                            .synOrAsy(true)//同步true或异步false 压缩 默认同步
                            .rotateEnabled(true) // 裁剪是否可旋转图片 true or false
                            .isDragFrame(false)// 是否可拖动裁剪框(固定)
                            .forResult(PictureConfig.CHOOSE_REQUEST);//结果回调onActivityResult code
                }
                break;
            case R.id.personal_head_edit:
                //todo 编辑
                break;
            case R.id.personal_my_gateway:
                Intent gatewayIntent = new Intent(mContext, GatewayListActivity.class);
                startActivity(gatewayIntent);
                break;
            case R.id.personal_my_auth:
                if (llAuthFold.getVisibility() == View.GONE) {
                    llAuthFold.setVisibility(View.VISIBLE);
                    ivAuthIcon.setImageResource(R.mipmap.fold);
                } else {
                    llAuthFold.setVisibility(View.GONE);
                    ivAuthIcon.setImageResource(R.mipmap.in);
                }
                break;
            case R.id.personal_message:
                Intent messageIntent = new Intent(mContext, MessageActivity.class);
                startActivity(messageIntent);
                break;
            case R.id.personal_logout:
                mPresenter.logout(SPUtils.newInstance().getString(SPUtils.LOGIN_TOKEN));
                break;
            case R.id.toolbar_left:
                finish();
                break;
            case R.id.personal_modify_password:
                //修改密码
                Intent modifyPasswordIntent = new Intent(mContext, ModifyPasswordActivity.class);
                startActivityForResult(modifyPasswordIntent, 500);
                break;
            case R.id.personal_auth_gateway:
                Intent authIntent = new Intent(mContext, GatewayAuthActivity.class);
                startActivity(authIntent);
                break;
            case R.id.personal_auth_monitor:
                Intent monitorAuthIntent = new Intent(mContext, EzDeviceAuthorizationActivity.class);
                startActivity(monitorAuthIntent);
                break;
            case R.id.personal_auth_door:
                //门锁授权
                Intent doorAuthIntent = new Intent(mContext, DoorAuthActivity.class);
                startActivity(doorAuthIntent);
                break;
        }
    }

    @Override
    public void viewUser(UserBean userBean) {
        UserBean.DataBean data = userBean.getData();
        Glide.with(mContext).load(ShouCheApis.HOST_ + data.getImage()).apply(new RequestOptions().error(R.mipmap.default_head)
                .placeholder(R.mipmap.default_head).circleCrop().diskCacheStrategy(DiskCacheStrategy.ALL)).into(ivHead);
        tvName.setText(data.getTelephone());
    }

    @Override
    public void viewModifyHead(ModifyHeadBean modifyHeadBean) {
        initData();
    }

    @Override
    public void viewLogout(CommonBean commonBean) {
        setResult(500);
        THOpenSDK.getInstance().logoutGateway();
        SPUtils.newInstance().remove(SPUtils.LOGIN_TOKEN);
        finish();
    }

    @Override
    protected void onActivityResult(int requestCode, int resultCode, Intent data) {
        super.onActivityResult(requestCode, resultCode, data);
        if (resultCode == RESULT_OK) {
            switch (requestCode) {
                case PictureConfig.CHOOSE_REQUEST:
                    // 图片选择
                    selectList = PictureSelector.obtainMultipleResult(data);
                    if (selectList.size() == 1) {
                        File file = new File(selectList.get(0).getCompressPath());
                        if (file.exists()) {
                            RequestBody requestBody = RequestBody.create(MediaType.parse("image/png"), file);
                            MultipartBody.Part part = MultipartBody.Part.createFormData("file", file.getName(), requestBody);
                            RequestBody token = RequestBody.create(null, SPUtils.newInstance().getString(SPUtils.LOGIN_TOKEN));
                            mPresenter.modifyHead(token, part);
                        }
                    }
                    // 例如 LocalMedia 里面返回三种path
                    // 1.media.getPath(); 为原图path
                    // 2.media.getCutPath();为裁剪后path，需判断media.isCut();是否为true
                    // 3.media.getCompressPath();为压缩后path，需判断media.isCompressed();是否为true
                    // 如果裁剪并压缩了，已取压缩路径为准，因为是先裁剪后压缩的
                    break;
            }
        } else if (resultCode == 500 && requestCode == 500) {
            setResult(500);
            finish();
        }
    }

    @Override
    public int getPermissionsRequestCode() {
        return 0;
    }

    @Override
    public String[] getPermissions() {
        return mPermissions;
    }

    @Override
    public void requestPermissionsSuccess() {
    }

    @Override
    public void requestPermissionsFail() {
        StringBuilder sb = new StringBuilder();
        mPermissions = PermissionUtil.getDeniedPermissions(this, mPermissions);
        if (mPermissions != null) {
            for (String s : mPermissions) {
                if (s.equals(Manifest.permission.CAMERA)) {
                    sb.append("相机权限(用于拍照，视频聊天);\n");
                } else if (s.equals(Manifest.permission.READ_EXTERNAL_STORAGE) || s.equals(Manifest.permission.WRITE_EXTERNAL_STORAGE)) {
                    sb.append("存储,读取权限(用于存储必要信息，缓存数据);\n");
                }
            }
        }
        PermissionUtil.PermissionDialog(this, "程序运行需要如下权限：\n" + sb.toString() + "请在应用权限管理进行设置！");
    }

    @Override
    public void onRequestPermissionsResult(int requestCode, @NonNull String[] permissions, @NonNull int[] grantResults) {
        if (permissionHelper.requestPermissionsResult(requestCode, mPermissions, grantResults)) {
            //权限请求结果，并已经处理了该回调
            return;
        }
        super.onRequestPermissionsResult(requestCode, permissions, grantResults);
    }
}
